package com.ruix.app.ui.stratum.lesson;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.OSS;
import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.OssTokenMapper;
import com.ruix.app.model.Classes;
import com.ruix.app.model.OssToken;
import com.ruix.app.network.ALUploadFileParam;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.PhotoAdapter;
import com.ruix.app.ui.adapter.RecyclerItemClickListener;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.stratum.ReleasePostsActivity;
import com.ruix.app.ui.stratum.notice.ReleaseNoiceActivity;
import com.ruix.app.util.ImageClipUtil;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.util.TackPicUtil;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.dialog.CommonDialog;
import com.ruix.app.widget.dialog.ReleaseLearningFeelDialog;
import com.ruix.app.widget.dialog.fragment.ListDialogFragment;
import com.ruix.app.widget.dialog.iface.IListDialogListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

/**
 * Created by hadexs on 2017/4/21.
 */

public class ReleaseLearningFeelActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener ,ReleaseLearningFeelDialog.AcitonListener,IListDialogListener {

    public static Intent newIntent(Context context,String leesonId,String lessonName) {
        Intent intent = new Intent(context, ReleaseLearningFeelActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("lessonName", lessonName);
        bundle.putSerializable("leesonId", leesonId);
        intent.putExtras(bundle);
        return intent;
    }

    //图片选择
    private EditText inputEditText;
    private Classes currentClasses;
    private String leesonId,lessonName;
    private PhotoAdapter photoAdapter;
    private RecyclerView recyclerView;
    private OSS ossClient;
    private OssToken ossToken;

    private ArrayList<String> selectedPhotos = new ArrayList<>();

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_release_learning_fell;
    }

    @Override
    protected void initView() {
        setTitle("发布");
        initCarrayData();
        inputEditText = (EditText) findViewById(R.id.et_content);
        inputEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        String deafultString = "#学以致用#";
        if (!TextUtils.isEmpty(lessonName)) {
             deafultString = String.format("#学以致用##%s#", lessonName);
        }
        inputEditText.setText(deafultString);
        inputEditText.setSelection(inputEditText.length());

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        photoAdapter = new PhotoAdapter(this, selectedPhotos);

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        recyclerView.setAdapter(photoAdapter);

        CommonTitleBar titleBar = getTitleBar();
        TextView titleBarRightBtn = titleBar.getRightBtn();
        titleBarRightBtn.setText("发送");
        titleBarRightBtn.setTextColor(getResources().getColor(R.color.green));
        titleBarRightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                releasePost();
            }
        });

        if (titleBar != null){
            titleBar.setOnClickLeftListener(new CommonTitleBar.OnTitleBarClickLeftListener() {
                @Override
                public void onClickLeftBackBtn() {
                    checkInput();
                }
            });
        }

    }

    private void initCarrayData(){
        Intent intent = getIntent();
        if (intent != null) {
            currentClasses = UserManager.sharedInstance().getCurrentClass();  //(Classes) intent.getSerializableExtra("classes");
            leesonId = intent.getStringExtra("leesonId");
            lessonName = intent.getStringExtra("lessonName");
        }

    }

    @Override
    protected void initLocalData() {
        loadOssTokenWithCache();

    }

    private void loadOssTokenWithCache() {
        String uid = UserManager.getCurrentUser().getID();
        ossToken = CacheFactory.loadOssToken(uid);
        if (ossToken != null && !TextUtils.isEmpty(ossToken.getSecurityToken())) {
            buildOssClient();
        } else {
            loadOssToken();
        }
    }

    private void buildOssClient() {
        if (ossToken != null) {
            ossClient = ALUploadFileParam.loadOSSClient(this, ossToken);
        }
    }

    private void loadOssToken() {
        RequestFactory.getOssToken(new OssTokenMapper(), new RXObserver<OssToken>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OssToken value) {
                if (value != null && !TextUtils.isEmpty(value.getSecurityToken())) {
                    ossToken = value;
                    buildOssClient();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void checkInput(){
        if (selectedPhotos != null && selectedPhotos.size() > 0) {
            exitTipDialog();
            return;
        }
        String inputContent =  inputEditText.getText().toString();
        if (!TextUtils.isEmpty(inputContent)){
            exitTipDialog();
            return;
        }
        finish();
    }

    private void exitTipDialog(){
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                finish();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("是否放弃内容？");
        dialog.setPositiveString("是");
        dialog.seCancelString("否");

    }

    @Override
    protected void initListener() {
//        findViewById(R.id.submit_btn).setOnClickListener(this);
        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                            showDialog();
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(ReleaseLearningFeelActivity.this);
                        }
                    }
                }));

        inputEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    SoftInputUtil.hideSoftInput(inputEditText);
                    uploadPhoto();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    private void releasePost() {
        if (selectedPhotos != null && selectedPhotos.size() > 0) {
            uploadPhoto();
        } else {
            String postsContent = inputEditText.getText().toString();
            if (TextUtils.isEmpty(postsContent)) {
                showErrorTip("请输入实践内容或图片");
                return;
            }
            showLoading();
            releasePost(null);
        }
    }


    private void releasePost(ArrayList<String> value) {
        String source;
        if (value != null) {
            source = bulidFileSource(value);
        } else {
            source = "";
        }
        String postsContent = inputEditText.getText().toString();
        RequestFactory.publishPosts(currentClasses.getID(), postsContent, source,leesonId, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                sendReleasePostSuccess();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                showErrorTip(e.getMessage());
            }

            @Override
            public void onComplete() {
                dismissLoading();
                showSuccessTip("发布成功");
                showTipDialog();
            }
        });

    }



    //上传图片
    private void uploadPhoto() {
        showLoading();//
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.setPathes(selectedPhotos);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                releasePost(value);
            }

            @Override
            public void onError(Throwable e) {
                showErrorTip(e.getMessage());
                dismissLoading();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private String bulidFileSource(ArrayList<String> value) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < value.size(); i++) {
            sb.append(value.get(i));
            if (i < value.size() - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();
            if (photos != null) {
                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }else if (requestCode == CAMERA_WITH_DATA && resultCode == RESULT_OK) {
            if (cameraImgUri != null) {
//                selectedPhotos.add(cameraImgUri.getPath());
                if (android.os.Build.VERSION.SDK_INT < 24) {
                    selectedPhotos.add(cameraImgUri.getPath());
                } else  {
                    try {
                        String path = TackPicUtil.getFilePathWithUri(cameraImgUri,this);
                        if (!TextUtils.isEmpty(path)) {
                            path =  Environment.getExternalStorageDirectory().getAbsolutePath() + path;
                            selectedPhotos.add(path);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            photoAdapter.notifyDataSetChanged();
        }else if (requestCode == REQUEST_CODE_CAMERA){
//            checkCameraPermission();
        }
    }

    private void sendReleasePostSuccess(){
        Intent intent = new Intent();
        intent.setAction(RuiXConstant.NOTICE_RELEASE_POST_SUCCESS);//RuiXConstant.NOTICE_CHANGE_SHARE_STATE
        sendOrderedBroadcast(intent,null);
    }


    private void showTipDialog(){
        ReleaseLearningFeelDialog dialog = new ReleaseLearningFeelDialog(this);
        dialog.setListener(this);
        dialog.show();
    }


    @Override
    public void positiveAction() {
        Intent intent = new Intent();
        intent.setAction(RuiXConstant.NOTICE_RELEASE_LESSON_SUCCESS_PRACTICE);
        sendOrderedBroadcast(intent,null);
        finish();
    }

    @Override
    public void negertivieAction() {

    }

    @Override
    public void dismisssAction() {
//        finish();
    }


    private final int DIALOG_REQUEST_CODE_SET_AVATAR = 0x02;
    private Uri cameraImgUri;
    private final int CAMERA_WITH_DATA = 1001;
    private final int REQUEST_CODE_CAMERA = 222;

    //选择照片
    private void showDialog(){
        String[] choosePic =new String[2];
        choosePic[0]= "照相";
        choosePic[1]= "从手机相册选择";
        ListDialogFragment.createBuilder(this)
                .setTitle("选择图片来源")
                .setPositiveButtonText(R.string.confirm)
                .setNegativeButtonText(R.string.cancel)
                .setItems(choosePic)
                .setSelectedItem(0)
                .setRequestCode(DIALOG_REQUEST_CODE_SET_AVATAR)
                .show();
    }


    @Override
    public void onListItemSelected(CharSequence value, int number, int requestCode) {
        switch (requestCode) {
            case DIALOG_REQUEST_CODE_SET_AVATAR:
                if (number == 0) {
                    checkCameraPermission();
                } else {
                    PhotoPicker.builder()
                            .setPhotoCount(9)
                            .setShowCamera(true)
                            .setPreviewEnabled(false)
                            .setSelected(selectedPhotos)
                            .start(ReleaseLearningFeelActivity.this);
                }
                break;
        }
    }

    private void takePic() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// TODO: 16/5/26  没有外置存储
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraImgUri = Uri.parse(Uri.fromFile(new File(ImageClipUtil.getCameraFileName(this))).toString());
            if (android.os.Build.VERSION.SDK_INT < 24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                cameraImgUri = FileProvider.getUriForFile(this.getApplicationContext(), "com.ruix.app.fileprovider", file);//通过FileProvider创建一个content类型的Uri
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);//将拍取的照片保存到指定URI
            }
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } else {
            showErrorTip("暂不支持");
        }
    }


    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ReleaseLearningFeelActivity.this, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_CAMERA);
                return;
            } else {
                takePic();//调用具体方法
            }
        } else {
            takePic();//调用具体方法
        }
    }

}
